var cf = require("../../config.js");
var util = require("../../utils/util.js");
var regeneratorRuntime = require("../../lib/js/runtime-module.js")
const pageManager = require('../../lib/js/pageManager');
import loadServ from "./loadServ";
//获取应用实例
var app = getApp();
Page({
  data: {
    requestShow: false,
    openOptions: [false],
    skipUserInfoOauth: true,
    list: [
      {name:'置业顾问',phone:'11111111111',labels: '[{"lab": "专业可靠", "num": 2}, {"lab": "贴心服务", "num": 2}]'},
      {name:'置业顾问',phone:'11111111111',labels: '[{"lab": "专业可靠", "num": 2}, {"lab": "贴心服务", "num": 2}]'},
      {name:'置业顾问',phone:'11111111111',labels: '[{"lab": "专业可靠", "num": 2}, {"lab": "贴心服务", "num": 2}]'}],
    relations: [], 
    isLoading: false,
    pageSize: 10,
    curPage: 0,
    total: 0,
    isBottom: false,
    reqUrl: "/applet/mobile/visitcard/memberrelation/findByMemberOpenId",
    isNotConcat: false,
    isFirstIn: true,
    isShowList: true,
    source: 2, //来源 0-扫描 1-分享 2-搜索 3-交接,
    relationMap: {}, //名片和用户的关系
    relation: false, //没有建立关系
    isSales: false, //是否是销售员
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    hasUserInfo: false,
    visitCardConfig: {},
    timer: null,
    noData: false,
    recommendData: [],//推荐楼盘
    showSkeleton: true,
    defaultImg: 'https://zysj-pro.oss-cn-shenzhen.aliyuncs.com/zysq-miniprogram/images/card/card_defaultImg.png',
  },
  /**
    * 生命周期函数--监听页面加载
    */
  onLoad(options) {
 
    let findByMemberOpenId = pageManager.getData('findByMemberOpenId');
    if(findByMemberOpenId){
      this.data.requestShow = true;
      findByMemberOpenId.then((res)=>{
        this.setData({
          showSkeleton: false,
          list:res.model.list
          });
        
        this.queryCardList(res)
     });
    }
   
    wx.setNavigationBarTitle({
      title: '我的名片夹',
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onHide() {
    this.data.requestShow = false;
  },
  onShow() {
    let that = this
    this.data.cusmallToken = wx.getStorageSync('cusmallToken');
    this.data.curPage = 0;
    if (!that.data.requestShow) {
      that.queryCardList();//先获取名片列表数据
    }
    app.getEmployeeInfo().then(() => {
      let employee = wx.getStorageSync('employee');
      that.setData({ isSales: employee.isSales })
    })
    app.getTotalUnreadNum(function (num) { });
  },
  /**
 * 获取最top名片列表
 */
  getTopThree: async function () {
    let that = this
    let param = {
      cityCode: app.globalData.cityData.cityadcode
    }
    let data = await loadServ.queryEmployeeByCityCode(param);
    if (data.length > 0) {
      data.map(item => {
        if (item.projectInfo) {
          item.projectInfo = JSON.parse(item.projectInfo);
        }

      })
      that.setData({
        list: data, noData: false
      })
    } else {
      that.setData({
        noData: true,showSkeleton:false
      });
    }

  },
  /**
   * 获取名片列表
   */
  queryCardList: async function (res) {
    var ctx = this;
    let { list, relation, relations, curPage, pageSize, total,cusmallToken,relationMap } = this.data;

    let param = {
      cusmallToken: cusmallToken,
      start: curPage * pageSize,
      limit: pageSize
    }
    let model = null;
    if(res){
       model = res.model
    }else{
      let data = await loadServ.findByMemberOpenId(param);
      model = data.model
    }
   
    if (model&&model.list.length > 0) {
      if (model && model.relation.length > 0) {
        var listData = model.list;
        var relationList = model.relation;
        if (listData.length == 0 && curPage == 0) {
          ctx.getTopThree()
          return;
        }
        if (curPage >= 1) {
          list = list.concat(listData);
          relations = relations.concat(relationList)
        } else {
          list = listData;
          relations = relationList
        }
        list.map((item, index) => {
          item.top = model.relation[index] && model.relation[index].top
          item.employeeOpenId = model.relation[index] && model.relation[index].employeeOpenId

          var card = item;
          if (!wx.getStorageSync("has_readmsg_" + card.id)) {
            card.unreadNum += 1;
          }
          // if (item.projectInfo) {
          // console.log(item.projectInfo)
          // item.projectInfo = JSON.parse(item.projectInfo)||'';
          // }
        })
        for (let item of relations) {
          item.sourceTxt = util.getCardSource(item.source);
          if (item.toEmployeeName) {
            item.toEmployeeName = util.cusSubString(item.toEmployeeName, 4);
          }
          relationMap[item.employeeId] = item
        }
        ctx.setData({
          showSkeleton: false, list, relations, total: model.total, relation: true,relationMap
        });
       
      }
    } else {
       ctx.setData({
        showSkeleton: false
       });
    }

  },
  /**
   * 更多的操作
   */

  showAction: function (e) {
    let { eid, top, employeeopenid } = e.currentTarget.dataset, that = this
    console.log(employeeopenid)
    wx.showActionSheet({
      itemList: [top + '' == '0' ? '置顶名片' : '取消置顶', '删除名片'],
      success(res) {
        let transList = []
        for (let i = 0; i < that.data.list.length; i++) {
          transList[i] = 0;
        }
        if (res.tapIndex == 0) {
          wx.request({
            url: `${cf.config.pageDomain}applet/mobile/visitcard/memberrelation/updateTop`,
            header: {
              'content-type': 'application/json'
            },
            data: {
              employeeId: eid,
              top: top + '' == '0' ? 1 : 0,
              cusmallToken: that.data.cusmallToken
            },
            success: function (res) {
              that.setData({
                curPage: 0
              })
              that.queryCardList()
            }
          })
        } else {
          wx.showModal({
            title: '提示',
            content: '是否确认删除',
            success(res) {
              let transList = []
              for (let i = 0; i < that.data.list.length; i++) {
                transList[i] = 0;
              }
              if (res.confirm) {
                wx.request({
                  url: `${cf.config.pageDomain}applet/mobile/visitcard/memberrelation/deleteCart`,
                  header: {
                    'content-type': 'application/json'
                  },
                  data: {
                    employeeId: eid,
                    cusmallToken: that.data.cusmallToken,
                  },
                  success: function (res) {
                    that.setData({
                      curPage: 0
                    })
                    that.queryCardList();
                    that.del(employeeopenid)
                  }
                })
              } else if (res.cancel) {
                wx.hideLoading()
              }
            }
          })
        }
      }
    })
  },
  //删除顾问在信息列表数据
  del: function (id) {
    let toaccount = id,chat_detail = wx.getStorageSync('chat_detail'),closeTipsUser = wx.getStorageSync('closeTipsUser'),
        fromAccount = wx.getStorageSync('openId');

    loadServ.delHistoryMsg({type:"1", fromAccount, toAccount: toaccount, cusmallToken: this.data.cusmallToken }).then((item) => {
      if (chat_detail[toaccount]) {//删除缓存
        delete chat_detail[toaccount]
        wx.setStorageSync('chat_detail', chat_detail)
      }
      if(closeTipsUser[toaccount]){ //删除提示弹出
        delete closeTipsUser[toaccount]
        wx.setStorageSync('closeTipsUser',closeTipsUser)
      }
    });
  },
  /**
   * 跳转洽谈室
   */
  gochatDetail: function (e) {
    let { eid, openid } = e.currentTarget.dataset
    this.setData({
      isNewsTip: false,
      card_detail_noread: 0
    })
    app.subscribeMessage(()=>{
      wx.navigateTo({
        url: "/subPackages/pages/chat_detail/chat_detail?eId=" + eid
      });
      
    },cf.config.messageTemplateId);

    wx.setStorageSync("has_readmsg_" + eid, true);
  },
  /**
   * 跳转美房详情
   */
  toHouseDetail: function (e) {
    
    if (e.currentTarget.dataset.projectid) {
      let productid = e.currentTarget.dataset.projectid + ''
      wx.request({
        url: `${cf.config.pageDomain}/api/counselor/getProjectInfoById`,
        header: {
          'content-type': 'application/json',
          'token': wx.getStorageSync('authName')
        },
        data: {
          projectId: productid
        },
        success: function (res) {
          const data = res.data.model.projectInfo
          if (res.data.ret == 0) {
            wx.navigateTo({
              url: `/subPackages/pages/buildingDetail/buildingDetail?productId=${data.productId}`
            })
          } else {
            wx.showToast({ title: '该楼盘暂无详细信息', icon: 'none' })
          }
        }
      })
    }
  },
  /**
   * 拨打电话
   */
  phone: function (e) {
    let { phone } = e.currentTarget.dataset;
    wx.makePhoneCall({
      phoneNumber: phone,
    })
  },
  /**
   * 跳转搜索列表
   */
  toGwlist: function () {
    wx.navigateTo({ url: '/pages/consultant/consultant?pageType=load' })
  },
  /**
  * 跳转名片详情
  */
  toTab: function (e) {
    var ctx = this;
    var eId = e.currentTarget.dataset.eid;
    if (!ctx.data.relationMap[eId]) { //没有关系才进行绑定
      util.addRelation(eId, this.data.cusmallToken, ctx.data.source);
    }
    wx.setStorageSync("eId", eId); //员工id
    wx.navigateTo({
      url: '/pages/mycard/card?eId=' + eId
    })
    var list = ctx.data.list;
    for (var i = 0; i < list.length; i++) {
      var card = list[i];
      if (card.id == eId) {
        card.unreadNum = 0;
        ctx.setData({
          ["list[" + i + "]"]: card
        });
      }
    }
  },
  // 调整到名片后台
  toSales: function () {
    wx.navigateTo({
      url: '/pages/sales/me/me',
    })
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    // debugger
    if (this.data.list.length >= this.data.total) {
      return
    }
    let ctx = this;
    ctx.setData({
      curPage: parseInt(ctx.data.curPage) + 1
    });
    ctx.queryCardList();
  },
  sendCard: function (e) {
    var index = e.target.dataset.index;
    var eid = e.target.dataset.eid;
    var ctx = this;
  },
  /**
   * 用户点击右上角
   */
  onShareAppMessage: function (e) {
    var ctx = this;
    var eId = e.target.dataset.eid;
    var myOpenid = wx.getStorageSync('openId');
    var userInfo = wx.getStorageSync('userInfo');
    if (e.from == "button" && eId) {
      let title = "";
      let cardInfo = {};
      for (let i = 0; i < ctx.data.list.length; i++) {
        if (ctx.data.list[i].id == eId) {
          cardInfo = ctx.data.list[i];
          break;
        }
      }

      if (null == cardInfo.shareSpeech) {
        title = "你好，我是" + (cardInfo.company || ctx.data.companyInfo.shortName) + '的' + cardInfo.name;
      } else {
        title = cardInfo.shareSpeech;
      }
      let path = "/pages/mycard/card?eId=" + eId + "&source=1";
      util.addBehaviorTrail(eId, 3);
      //path 添加客户来源
      path += "&fromOpenId=" + myOpenid + "&fromNickName=" + userInfo.nickName + "&forwardType=page_card";
      let shareObj = {
        title: title,
        path: path,
        imageUrl: cardInfo.headPic,
        success: function (res) { },
        fail: function (res) { }
      };
      return shareObj;
    }
  }
})
